package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.area.model.entity.Area;
import com.wing.area.service.AreaService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.Agent;
import com.wing.sell.model.entity.AgentCategory;
import com.wing.sell.model.entity.AgentLevel;
import com.wing.sell.model.request.AgentForm;
import com.wing.sell.service.AgentCategoryService;
import com.wing.sell.service.AgentLevelService;
import com.wing.sell.service.AgentService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-销售代理商经销申请记录管理", tags = "#/sell/agentApply")
@RestController("agentApplyController")
@RequestMapping("sell/admin/agentApply")
@RequiredArgsConstructor
public class AgentApplyController {

    private final AgentService agentService;
    private final AgentCategoryService agentCategoryService;
    private final AgentLevelService agentLevelService;
    private final AreaService areaService;


    @ApiOperation(value = "查询所有销售代理商经销记录", notes = "申请搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "provinceId", value = "省id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "agentCategoryId", value = "代理商分类", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "agtLevel", value = "代理商所属级别", defaultValue = "", example = "", dataType = "Long", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "代理商名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "licenseNo", value = "营业执照号", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "status", value = "状态", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<Agent> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long provinceId
            ,Long agentCategoryId
            ,Long agtLevel
            ,String name
            ,String licenseNo
            ,String status
    ){

        Page<Agent> pg = new Page<>(page, limit);
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索
        if (provinceId !=null){
            queryWrapper.eq("province_id", provinceId);
        }
        if (agentCategoryId !=null){
            queryWrapper.eq("agent_category_id", agentCategoryId);
        }
        if (agtLevel !=null){
            queryWrapper.eq("agt_level", agtLevel);
        }
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(licenseNo)) {
            queryWrapper.like("license_no", licenseNo);
        }
        if(null != status){
            queryWrapper.in("status", Arrays.asList(status.split(",")));
        }

        IPage<Agent> list = agentService.getBaseMapper().selectPage(pg, queryWrapper);
        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            //分类名称
            AgentCategory agentCategory = agentCategoryService.getById(k.getAgentCategoryId());
            if(null != agentCategory) {
                k.setAgentCategoryName(agentCategory.getName());
            }
            //代理级别名称
            AgentLevel agentLevel = agentLevelService.getById(k.getAgtLevel());
            if(null != agentLevel) {
                k.setAgtLevelName(agentLevel.getName());
            }
            //省份名称
            Area area = areaService.getById(k.getProvinceId());
            if(null != area) {
                k.setProvinceName(area.getAreaname());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加销售代理商经销记录", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(AgentForm.Add.class) AgentForm agentForm) {
        if (agentService.add(agentForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改销售代理商经销记录", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(AgentForm.Update.class) AgentForm agentForm) {
        Agent agent = agentService.getById(agentForm.getId());
        if(agent == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Agent.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(agentForm, agent, copyOptions);
        if (agentService.updateById(agent)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "审核销售代理商经销申请记录", notes = "审核")
    @GetMapping("/check")
    public JsonResult check(Long agtId) {
        Agent agent = agentService.getById(agtId);
        if(agent == null){
            return JsonResult.fail("审核失败！");
        }
        if(agent.getStatus().getValue() != Agent.Status.wait_check.getValue()){
            return JsonResult.fail("审核失败！状态不是待审核");
        }
        agent.setStatus(Agent.Status.wait_qianyue);
        if (agentService.updateById(agent)) {
            return JsonResult.success("审核成功！");
        }
        return JsonResult.fail("审核失败！");
    }



    @ApiOperation(value = "删除销售代理商经销记录", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agentId", value = "销售代理商经销记录id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long agentId) {
        if (agentService.removeById(agentId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
